/**
 * Created by wangkui on 2015/8/28.
 */
var express = require('express');
var router = express.Router();
var request = require('request');
var huaweictl = require('./huawei.controller');
var User = require('./../../models/schema/userSchema.js');
var config = require('./../../config');
var crypto=require('crypto');
var async = require("async");
var http=require('http');
var fs = require("fs");
var Wechat=require('./../../bpswechat');
var wxsign = require('./wxsign');
var url = require("url");

router.get('/',function(req, res, next){
    var wxUser = {
        openid:'',
        unionid:'',
        nickname:'未登录',
        sex:'',
        province:'',
        city:'',
        country:'',
        headimgurl:'',
        flag:''
    };
    //未过期
    if (req.cookies.a_h != null){
        var flag='';
        if(req.cookies.flag!=null && req.cookies.flag=='1'){
            flag='1';
            res.cookie('flag', '0', {maxAge: 60*60 * 1000});
        }else{
            flag='0';
        }

        var headimgurl=decrypt(req.cookies.a_h,config.secrets.session);
        var openid=decrypt(req.cookies.a_o,config.secrets.session);
        var nickname=decrypt(req.cookies.a_n,config.secrets.session);
        var sex=decrypt(req.cookies.a_s,config.secrets.session);
        var ck = {
            openid:openid,
            nickname:nickname,
            headimgurl:headimgurl,
            unionid:'',
            sex:sex,
            province:'',
            city:'',
            country:'',
            flag:flag
        };
        res.render('huawei', {wxUser:ck});
    }else{
        res.render('huawei', {wxUser:wxUser });
    }
});
//保存登录前状态值
router.get('/savebiaozhu',function(req,res,next){
    res.cookie('flag', '1', {maxAge: 30 * 1000});
    res.json(201,"ok");
});
//微信登录
router.get('/callback',function(req,res,next){
    var code=req.query.code;
    var openid='';
    var unionid='';
    var access_token='';
    var nickname='';
    var sex='';
    var province='';
    var city='';
    var country='';
    var headimgurl='';
    var wxdata;

    async.series({
        first:function(callback){
            //通过code得到token.openid
            var wx_url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx52cb16abd04ebee3&secret=6df0bf588ccef3d76c4ae15cbe0d8049&code="+code
                +"&grant_type=authorization_code";
            request.get({url: wx_url, json: true}, function (error, response, body){
                if(error){
                    //logger.error(error);
                    callback();}
                if (!error && response.statusCode === 200)
                {
                    openid = body.openid;
                    unionid = body.unionid;
                    access_token=body.access_token;
                }
                callback();
            });
        }
        ,
        second:function(callback){
            //通过openid获取用户信息，并保持用户信息
            var url="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
            request.get({url: url, json: true}, function (error, resp, data){
                if(error){
                    //logger.error(error);
                    callback();}
                if (!error && resp.statusCode === 200){
                    nickname=data.nickname;
                    sex=data.sex;
                    province=data.province;
                    city=data.city;
                    country=data.country;
                    headimgurl=data.headimgurl;
                }
                callback();
            });
        }
    },function(err,results){
        //保存登录信息到cookie中
        //数据加密写入Cookie,过期时间为30天后
        var en_openid=encrypt(openid,config.secrets.session);
        var en_headimgurl=encrypt(headimgurl,config.secrets.session);
        var en_nickname=encrypt(nickname,config.secrets.session);
        var en_sex=encrypt(sex,config.secrets.session);

        res.cookie('a_o', en_openid, {maxAge:  30*24*60*60 * 1000});
        res.cookie('a_h', en_headimgurl, {maxAge: 30*24*60*60 * 1000});
        res.cookie('a_n', en_nickname, {maxAge: 30*24*60*60 * 1000});
        res.cookie('a_s', en_sex, {maxAge: 30*24*60*60 * 1000});

        res.redirect('/huawei/');
    });
});

router.post('/saveuser',function(req,res){
    saveuserinfo(req.body.unionid,req.body.openid,req.body.nickname,req.body.sex,req.body.country,req.body.province,req.body.city,req.body.headimgurl,function(){
        res.send(200,"save is ok");
    })
})

//保存微信用户信息
function saveuserinfo(unionid,openid,nickname,sex,country,province,city,headimgurl,callback){
    if(unionid==undefined||unionid==''){
        callback();
    }
    User.find({"unionid":unionid},function(err,user){
        if(user.length===0){
            var sday=getbilldatelog();         //登录日期戳
            //定义一个新的数据集合：拆分前端传来的数据
            var newUser=new User({
                unionid:unionid,
                openid:openid,
                nickname:nickname,
                headimgurl:headimgurl,
                country:country,
                province:province,
                city:city,
                sex:sex,
                nums:0,
                sday:sday
            });
            User.create(newUser, function(err, data) {
                if(err) { callback(); }
                callback();
            });
        }else{
            callback();
        }
    });
}
//设置标签
router.post('/setbiaozhu',huaweictl.setbiaozhu);
//读取标签
router.get('/getbiaozhu/:id',huaweictl.getbiaozhu);
//读取全部标签
router.get('/getbiaozhu/',huaweictl.getAllbiaozhu);
//分页查询数据
router.get('/querybiaozhu/',huaweictl.getbiaozhubyskip);
//根据openid查询数据
router.get('/getbzbyopenid/:id',huaweictl.getbiaozhubyopenid);
//下载微信头像
router.get('/wxhead',huaweictl.getwxheadimgs);
//揭秘
router.get('/sec',function(req, res, next){
    res.render('huawei/sec');
});
//双镜头
router.get('/dec',function(req, res, next){
    res.render('huawei/dec');
});
//评论
router.get('/comment',function(req, res, next){
    res.render('huawei/comment');
});
//获取微信头像
router.get('/getpic',function(req,res,next){
    try{
        var url=req.query.url;
        request.get(url).pipe(res);
    }catch(e){
        res.send(200,'');
    }
});
//获取微信分享签名
router.get('/wxsign',function(req,res,next){
    var arg=url.parse(req.url,true).query;

    var wechat;
    var conf = {
        appid:"wx26fe4ccc982d1e1b",
        appsecret:"6d8ac447fd198ddeef5268d6c7976697",
        cache_ttl:7000
    };
    wechat = Wechat.create(conf);

    wechat.getJsApiSignature(arg.url,function(signdata){
        console.log(signdata);
        res.send(200,signdata);
    })
})

router.get('/wx',wxsign.getsignature);
//加密
function encrypt(str, secret) {
    //var cipher = crypto.createCipher('aes192', secret);
    //var enc = cipher.update(str, 'utf8', 'hex');
    //enc += cipher.final('hex');
    return str;
}
//解密
function decrypt(str, secret) {
    //var decipher = crypto.createDecipher('aes192', secret);
    //var dec = decipher.update(str, 'hex', 'utf8');
    //dec += decipher.final('utf8');
    return str;
}
//生成当前天的时间戳作为数据库日期查询段标签
function getbilldatelog(){
    var now=new Date();
    var intyear=parseInt(now.getFullYear());
    var intmonth=parseInt(now.getMonth())+1;
    var intday=parseInt(now.getDate());

    if(intmonth<10)
    {
        smonth="0"+intmonth.toLocaleString();
    }
    else
    {
        smonth=intmonth.toLocaleString();
    }

    if(intday<10)
    {
        sday="0"+intday.toLocaleString();
    }
    else
    {
        sday=intday.toLocaleString();
    }

    log=intyear.toLocaleString()+smonth.toLocaleString()+sday.toLocaleString();
    return log;
}

module.exports = router;